#include "glwidget.h"
#include <QMouseEvent>
#include <QKeyEvent>
#include <QWheelEvent>
#include <vector>
#include <cmath>
#include <GL/gl.h>
#include <GL/glu.h>
#include <QOpenGLWidget>
#include <QDebug>
#include <QPainter>
#include <QImage>
#include <QGLWidget>
#include <cstdlib>
#include <ctime>
#include <QTimer> // Added QTimer header
#include <QVector3D>
#include <QMatrix4x4>
#include <QSvgRenderer>
#include <QPixmap>


// 修改Node结构体定义
std::vector<GLWidget::Node> g_nodes;
GLWidget::Node* selectedNode = nullptr;
GLuint textures[3];

void drawSphere(float x, float y, float z, float radius);

void drawCube(float size) {
    glBegin(GL_QUADS);
    // Front face
    glVertex3f(-size, -size, size);
    glVertex3f(size, -size, size);
    glVertex3f(size, size, size);
    glVertex3f(-size, size, size);
    // Back face
    glVertex3f(-size, -size, -size);
    glVertex3f(size, -size, -size);
    glVertex3f(size, size, -size);
    glVertex3f(-size, size, -size);
    // Left face
    glVertex3f(-size, -size, -size);
    glVertex3f(-size, -size, size);
    glVertex3f(-size, size, size);
    glVertex3f(-size, size, -size);
    // Right face
    glVertex3f(size, -size, -size);
    glVertex3f(size, -size, size);
    glVertex3f(size, size, size);
    glVertex3f(size, size, -size);
    // Top face
    glVertex3f(-size, size, -size);
    glVertex3f(size, size, -size);
    glVertex3f(size, size, size);
    glVertex3f(-size, size, size);
    // Bottom face
    glVertex3f(-size, -size, -size);
    glVertex3f(size, -size, -size);
    glVertex3f(size, -size, size);
    glVertex3f(-size, -size, size);
    glEnd();
}

void drawTorus(float innerRadius, float outerRadius) {
    int numMajor = 20;
    int numMinor = 20;
    for (int i = 0; i < numMajor; ++i) {
        float a0 = i * 2.0f * M_PI / numMajor;
        float a1 = (i + 1) * 2.0f * M_PI / numMajor;
        float x0 = std::cos(a0);
        float y0 = std::sin(a0);
        float x1 = std::cos(a1);
        float y1 = std::sin(a1);

        glBegin(GL_TRIANGLE_STRIP);
        for (int j = 0; j <= numMinor; ++j) {
            float b = j * 2.0f * M_PI / numMinor;
            float c = std::cos(b);
            float r = innerRadius * c + outerRadius;
            float z = innerRadius * std::sin(b);

            glVertex3f(x0 * r, y0 * r, z);
            glVertex3f(x1 * r, y1 * r, z);
        }
        glEnd();
    }
}

// 修改构造函数中的相机参数
// 修改构造函数中的初始参数
GLWidget::GLWidget(QWidget *parent)
    : QOpenGLWidget(parent),
      m_viewDirty(true),
      m_rotationAxis(0, 1, 0),
      m_rotation(),
      m_translation(0, 0, 0),
      cameraDistance(50.0f),
      rotationX(-30.0f),
      rotationY(45.0f),
      targetRotationX(-30.0f),
      targetRotationY(45.0f),
      targetCameraDistance(50.0f),
      minCameraDistance(5.0f),
      maxCameraDistance(500.0f),
      isDragging(false),
      displayListsCreated(false)
{
    setFocusPolicy(Qt::StrongFocus);
    planes.clear();

    // Setup smooth animation timer
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this]() {
        updateCameraSmooth();
        update();
    });
    timer->start(16); // 60 FPS
}

GLWidget::~GLWidget() {
    deleteDisplayLists();
}

GLuint GLWidget::loadTexture(const QString &filePath) {
    QImage image;
    
    // 检查是否为SVG文件
    if (filePath.endsWith(".svg", Qt::CaseInsensitive)) {
        // 加载SVG文件
        QSvgRenderer svgRenderer(filePath);
        if (!svgRenderer.isValid()) {
            qWarning("Failed to load SVG texture: %s", qPrintable(filePath));
            return 0;
        }
        
        // 创建一个512x512的QPixmap来渲染SVG
        QPixmap pixmap(512, 512);
        pixmap.fill(Qt::transparent);
        
        // 将SVG渲染到QPixmap上
        QPainter painter(&pixmap);
        painter.setRenderHint(QPainter::Antialiasing, true);
        svgRenderer.render(&painter);
        painter.end();
        
        // 将QPixmap转换为QImage
        image = pixmap.toImage();
    } else {
        // 加载普通图片文件（PNG, JPG等）
        if (!image.load(filePath)) {
            qWarning("Failed to load texture: %s", qPrintable(filePath));
            return 0;
        }
    }
    
    image = QGLWidget::convertToGLFormat(image);
    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    
    // 使用gluBuild2DMipmaps生成高质量mipmap
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.width(), image.height(), GL_RGBA, GL_UNSIGNED_BYTE, image.bits());
    
    // 设置高质量纹理过滤参数
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    
    return texture;
}

// 在initializeGL中强制添加测试节点
void GLWidget::initializeGL() {
    initializeOpenGLFunctions();
    
    // 基本设置
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    
    // 深度测试设置
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glClearDepth(1.0f);
    
    // 面剔除设置
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CCW);
    
    // 混合设置
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    
    // 启用平滑着色
    glShadeModel(GL_SMOOTH);
    
    // 设置垂直同步以减少闪屏
    setFormat(QSurfaceFormat());
    QSurfaceFormat format = this->format();
    format.setSwapInterval(1); // 启用垂直同步
    setFormat(format);

    // int layerSizes[] = {30, 20, 30};
    // float layerZ[] = {-3.0f, 0.0f, 3.0f};
    // g_nodes.clear();
    // srand(time(0)); // seed the random number generator
    // for (int i = 0; i < 3; ++i) {
    //     for (int j = 0; j < layerSizes[i]; ++j) {
    //         float radius = 2.0f + static_cast<float>(std::rand()) / RAND_MAX * 1.0f;
    //         float angle = static_cast<float>(j) / layerSizes[i] * 2.0f * M_PI;
    //         g_nodes.push_back({radius * std::cos(angle), radius * std::sin(angle), layerZ[i]});
    //     }
    // }
    textures[0] = loadTexture(":/images/phone_hd.svg");
    textures[1] = loadTexture(":/images/router_hd.svg");
    textures[2] = loadTexture(":/images/computer_hd.svg");
    
    // 启用面剔除和深度测试
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glEnable(GL_DEPTH_TEST);
    
    // 设置光照
    setupLighting();
    
    // 优化渲染性能
    optimizeRendering();
    
    
    // 在平面上随机添加10个节点
//    srand(time(0));
//    for(int i=0; i<10; i++) {
//        float x = (rand() % 2000 - 1000) / 100.0f; // -10.0到10.0之间的随机x坐标
//        float y = (rand() % 2000 - 1000) / 100.0f; // -10.0到10.0之间的随机y坐标
//        NodeType type = static_cast<NodeType>(rand() % 3); // 随机节点类型
//        addNodeToPlane(0, x, y, type); // 添加到第一个平面
//    }
}


// 保留正确的createPlane实现
void GLWidget::createPlane(float zLevel, float size, const QColor& gridColor) {
    planes.push_back({zLevel, size, gridColor, {}});
    update();
}

// 添加平面节点
void GLWidget::addNodeToPlane(int planeIndex, float x, float y, NodeType type) {
    if(planeIndex >= 0 && planeIndex < planes.size()) {
        g_nodes.push_back({
                            x,  // 相对X坐标
                            y,  // 相对Y坐标（在XZ平面上的Z坐标）
                            planes[planeIndex].zLevel + 2.0f, // 节点图标中心的绝对高度
                            false,
                            type
                        });
        planes[planeIndex].nodeIndices.push_back(g_nodes.size()-1);
    }
    update();
}

// 生成随机连接（在paintGL前调用）
void GLWidget::generateRandomConnections(int planeIndex, int minConnections, int maxConnections) {
    if(planeIndex < 0 || planeIndex >= planes.size()) return;
    
    auto& plane = planes[planeIndex];
    
    for(int nodeIdx : plane.nodeIndices) {
        int connectionCount = minConnections + rand() % (maxConnections - minConnections + 1);
        for(int i = 0; i < connectionCount; i++) {
            int target = plane.nodeIndices[rand() % plane.nodeIndices.size()];
            if(nodeIdx != target) {
                // 避免重复连接
                bool exists = false;
                for(const auto& conn : connections) {
                    if((conn.node1 == nodeIdx && conn.node2 == target) ||
                       (conn.node1 == target && conn.node2 == nodeIdx)) {
                        exists = true;
                        break;
                    }
                }
                if(!exists) {
                    connections.push_back({nodeIdx, target, planeIndex, planeIndex});
                }
            }
        }
    }
    
    // 存储连接数据（需在类中添加 connections 成员变量）
    // connections.insert(connections.end(), newConnections.begin(), newConnections.end());
    update();
}

void GLWidget::generateInterPlaneConnections(int sourcePlane, int targetPlane, int connectionCount) {
    if (sourcePlane < 0 || sourcePlane >= planes.size() || 
        targetPlane < 0 || targetPlane >= planes.size() || 
        sourcePlane == targetPlane) {
        return;
    }
    
    const auto& sourceNodes = planes[sourcePlane].nodeIndices;
    const auto& targetNodes = planes[targetPlane].nodeIndices;
    
    if (sourceNodes.empty() || targetNodes.empty()) {
        return;
    }
    
    for (int i = 0; i < connectionCount; ++i) {
        int sourceNodeIdx = sourceNodes[rand() % sourceNodes.size()];
        int targetNodeIdx = targetNodes[rand() % targetNodes.size()];
        
        // 检查是否已存在连接
        bool exists = false;
        for (const auto& conn : connections) {
            if ((conn.node1 == sourceNodeIdx && conn.node2 == targetNodeIdx) ||
                (conn.node1 == targetNodeIdx && conn.node2 == sourceNodeIdx)) {
                exists = true;
                break;
            }
        }
        
        if (!exists) {
            connections.push_back({sourceNodeIdx, targetNodeIdx, sourcePlane, targetPlane});
        }
    }
}

void GLWidget::arrangeNodesInCircle(int planeIndex) {
    if (planeIndex < 0 || planeIndex >= planes.size()) return;
    
    const auto& nodeIndices = planes[planeIndex].nodeIndices;
    if (nodeIndices.empty()) return;
    
    // 大幅增大半径，让节点更加离散
    float radius = 6.0f; // 从3.0f增加到6.0f
    float angleStep = 2.0f * M_PI / nodeIndices.size();
    
    for (int i = 0; i < nodeIndices.size(); ++i) {
        float angle = i * angleStep;
        // 添加随机偏移，让圆形布局更自然
        float randomOffset = ((float)rand() / RAND_MAX - 0.5f) * 1.0f;
        float actualRadius = radius + randomOffset;
        g_nodes[nodeIndices[i]].relativeX = actualRadius * cos(angle);
        g_nodes[nodeIndices[i]].relativeY = actualRadius * sin(angle);
    }
}

void GLWidget::arrangeNodesInGrid(int planeIndex, int cols) {
    if (planeIndex < 0 || planeIndex >= planes.size()) return;
    
    const auto& nodeIndices = planes[planeIndex].nodeIndices;
    if (nodeIndices.empty()) return;
    
    int rows = (nodeIndices.size() + cols - 1) / cols;
    // 大幅增大网格范围和间距，让节点更加离散
    float gridSize = 10.0f; // 从5.0f增加到10.0f
    float spacingX = gridSize / (cols + 1);
    float spacingY = gridSize / (rows + 1);
    float halfGrid = gridSize / 2.0f;
    
    for (int i = 0; i < nodeIndices.size(); ++i) {
        int row = i / cols;
        int col = i % cols;
        
        // 添加小幅随机偏移，让网格布局更自然
        float randomX = ((float)rand() / RAND_MAX - 0.5f) * 0.5f;
        float randomY = ((float)rand() / RAND_MAX - 0.5f) * 0.5f;
        
        g_nodes[nodeIndices[i]].relativeX = -halfGrid + (col + 1) * spacingX + randomX;
        g_nodes[nodeIndices[i]].relativeY = -halfGrid + (row + 1) * spacingY + randomY;
    }
}

void GLWidget::arrangeNodesRandomly(int planeIndex, float margin) {
    if (planeIndex < 0 || planeIndex >= planes.size()) return;
    
    const auto& nodeIndices = planes[planeIndex].nodeIndices;
    if (nodeIndices.empty()) return;
    
    // 大幅增大分布范围，让节点更加离散
    float range = 8.0f - margin; // 从3.5f增加到8.0f
    float minDistance = 1.5f; // 从0.8f增加到1.5f
    
    for (int nodeIdx : nodeIndices) {
        bool validPosition = false;
        int attempts = 0;
        float x, y;
        
        while (!validPosition && attempts < 200) { // 增加尝试次数
            x = ((float)rand() / RAND_MAX) * 2.0f * range - range;
            y = ((float)rand() / RAND_MAX) * 2.0f * range - range;
            
            // 检查与其他节点的最小距离
            validPosition = true;
            for (int otherIdx : nodeIndices) {
                if (otherIdx != nodeIdx) {
                    float dx = x - g_nodes[otherIdx].relativeX;
                    float dy = y - g_nodes[otherIdx].relativeY;
                    float distance = sqrt(dx * dx + dy * dy);
                    
                    if (distance < minDistance) {
                        validPosition = false;
                        break;
                    }
                }
            }
            attempts++;
        }
        
        // 使用找到的有效位置，或者在失败时使用最后生成的位置
        g_nodes[nodeIdx].relativeX = x;
        g_nodes[nodeIdx].relativeY = y;
    }
}



void GLWidget::setupLighting() {
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
    
    // 设置光源位置
    GLfloat lightPos[] = {5.0f, 10.0f, 5.0f, 1.0f};
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
    
    // 设置光源颜色
    GLfloat lightAmbient[] = {0.3f, 0.3f, 0.3f, 1.0f};
    GLfloat lightDiffuse[] = {0.8f, 0.8f, 0.8f, 1.0f};
    GLfloat lightSpecular[] = {1.0f, 1.0f, 1.0f, 1.0f};
    
    glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse);
    glLightfv(GL_LIGHT0, GL_SPECULAR, lightSpecular);
    
    // 设置材质属性
    GLfloat matSpecular[] = {0.5f, 0.5f, 0.5f, 1.0f};
    GLfloat matShininess[] = {50.0f};
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, matSpecular);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, matShininess);
}

void GLWidget::drawEnhancedCube(float x, float y, float z, float width, float height, float depth, float r, float g, float b, float alpha) {
    glPushMatrix();
    glTranslatef(x, y, z);
    glScalef(width, height, depth);
    
    glColor4f(r, g, b, alpha);
    
    glBegin(GL_QUADS);
    
    // 前面
    glNormal3f(0.0f, 0.0f, 1.0f);
    glVertex3f(-0.5f, -0.5f,  0.5f);
    glVertex3f( 0.5f, -0.5f,  0.5f);
    glVertex3f( 0.5f,  0.5f,  0.5f);
    glVertex3f(-0.5f,  0.5f,  0.5f);
    
    // 后面
    glNormal3f(0.0f, 0.0f, -1.0f);
    glVertex3f(-0.5f, -0.5f, -0.5f);
    glVertex3f(-0.5f,  0.5f, -0.5f);
    glVertex3f( 0.5f,  0.5f, -0.5f);
    glVertex3f( 0.5f, -0.5f, -0.5f);
    
    // 顶面
    glNormal3f(0.0f, 1.0f, 0.0f);
    glVertex3f(-0.5f,  0.5f, -0.5f);
    glVertex3f(-0.5f,  0.5f,  0.5f);
    glVertex3f( 0.5f,  0.5f,  0.5f);
    glVertex3f( 0.5f,  0.5f, -0.5f);
    
    // 底面
    glNormal3f(0.0f, -1.0f, 0.0f);
    glVertex3f(-0.5f, -0.5f, -0.5f);
    glVertex3f( 0.5f, -0.5f, -0.5f);
    glVertex3f( 0.5f, -0.5f,  0.5f);
    glVertex3f(-0.5f, -0.5f,  0.5f);
    
    // 右面
    glNormal3f(1.0f, 0.0f, 0.0f);
    glVertex3f( 0.5f, -0.5f, -0.5f);
    glVertex3f( 0.5f,  0.5f, -0.5f);
    glVertex3f( 0.5f,  0.5f,  0.5f);
    glVertex3f( 0.5f, -0.5f,  0.5f);
    
    // 左面
    glNormal3f(-1.0f, 0.0f, 0.0f);
    glVertex3f(-0.5f, -0.5f, -0.5f);
    glVertex3f(-0.5f, -0.5f,  0.5f);
    glVertex3f(-0.5f,  0.5f,  0.5f);
    glVertex3f(-0.5f,  0.5f, -0.5f);
    
    glEnd();
    glPopMatrix();
}

void GLWidget::drawEnhancedNode(const Node& node, float planeHeight) {
    glPushMatrix();
    
    // 节点位置：球心位于平面上方固定距离
    const float nodeHeight = 2.0f; // 球心高度
    glTranslatef(node.relativeX, node.relativeY, planeHeight + nodeHeight);
    
    // 启用纹理和透明度
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    
    // 根据节点类型选择纹理和大小
    float radius = 0.8f;
    GLuint textureId;
    
    switch(node.type) {
        case DEVICE_PHONE:
            textureId = textures[0]; // phone.png
            radius = 0.6f;
            break;
        case DEVICE_ROUTER:
            textureId = textures[1]; // router.png
            radius = 0.8f;
            break;
        case DEVICE_COMPUTER:
            textureId = textures[2]; // computer.png
            radius = 1.0f;
            break;
        default:
            textureId = textures[0];
            radius = 0.8f;
            break;
    }
    
    // 绑定纹理
    glBindTexture(GL_TEXTURE_2D, textureId);
    
    // 启用光照以获得更好的3D效果
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    
    // 设置材质属性以增强球体效果
    GLfloat mat_ambient[] = {0.3f, 0.3f, 0.3f, 1.0f};
    GLfloat mat_diffuse[] = {0.8f, 0.8f, 0.8f, 1.0f};
    GLfloat mat_specular[] = {1.0f, 1.0f, 1.0f, 1.0f};
    GLfloat mat_shininess[] = {50.0f};
    
    glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
    glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
    
    // 设置颜色
    if (node.selected) {
        glColor4f(1.5f, 1.5f, 1.0f, 1.0f); // 选中时发黄光
    } else {
        glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // 正常白色
    }
    
    // 设置纹理参数以获得更好的效果
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    
    // 创建球体对象
    GLUquadricObj* sphere = gluNewQuadric();
    gluQuadricTexture(sphere, GL_TRUE); // 启用纹理映射
    gluQuadricNormals(sphere, GLU_SMOOTH); // 平滑法线
    gluQuadricDrawStyle(sphere, GLU_FILL); // 填充模式
    
    // 设置纹理环境模式以获得更好的纹理效果
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    
    // 绘制高质量球体 - 增加细分度以获得更平滑的表面和更好的纹理映射
    gluSphere(sphere, radius, 64, 32); // 半径，经线数64，纬线数32（提高细分度）
    
    // 清理球体对象
    gluDeleteQuadric(sphere);
    
    // 禁用纹理
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_BLEND);
    
    glPopMatrix();
}

int GLWidget::getNodeAtPosition(int x, int y) {
    // 将屏幕坐标转换为OpenGL坐标
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;
    
    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);
    
    winX = (float)x;
    winY = (float)viewport[3] - (float)y; // 翻转Y坐标
    glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
    
    gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
    
    // 检查哪个节点最接近点击位置
    float minDistance = 1000.0f;
    int selectedNodeIndex = -1;
    
    for (int i = 0; i < g_nodes.size(); ++i) {
        const Node& node = g_nodes[i];
        float dx = posX - node.relativeX;
        float dy = posY - node.relativeY;
        float dz = posZ - node.z;
        float distance = sqrt(dx * dx + dy * dy + dz * dz);
        
        if (distance < 0.2f && distance < minDistance) {
            minDistance = distance;
            selectedNodeIndex = i;
        }
    }
    
    return selectedNodeIndex;
}

void GLWidget::selectNode(int nodeIndex) {
    if (nodeIndex >= 0 && nodeIndex < g_nodes.size()) {
        // 清除之前的选择
        clearSelection();
        
        // 选择新节点
        g_nodes[nodeIndex].selected = true;
        selectedNode = &g_nodes[nodeIndex];
        
        update(); // 重新绘制
    }
}

void GLWidget::clearSelection() {
    for (Node& node : g_nodes) {
        node.selected = false;
    }
    selectedNode = nullptr;
}

void GLWidget::createDisplayLists() {
    if (displayListsCreated) {
        deleteDisplayLists();
    }
    
    // 创建平面显示列表
    planeDisplayList = glGenLists(1);
    glNewList(planeDisplayList, GL_COMPILE);
    drawTorus(10.0f, 1.0f);
    glEndList();
    
    // 创建节点显示列表
    nodeDisplayList = glGenLists(1);
    glNewList(nodeDisplayList, GL_COMPILE);
    drawEnhancedCube(0, 0, 0, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f);
    glEndList();
    
    displayListsCreated = true;
}

void GLWidget::deleteDisplayLists() {
    if (displayListsCreated) {
        glDeleteLists(planeDisplayList, 1);
        glDeleteLists(nodeDisplayList, 1);
        displayListsCreated = false;
    }
}

void GLWidget::optimizeRendering() {
    // 启用深度测试优化
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    
    // 启用面剔除
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    
    // 优化光照计算
    glEnable(GL_NORMALIZE);
    
    // 创建显示列表
    createDisplayLists();
}



// 添加并实现resizeGL函数
void GLWidget::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    
    // 优化投影矩阵设置
    float aspect = (float)w / (float)h;
    float zNear = 1.0f;
    float zFar = 100.0f;
    float fov = 45.0f;
    
    // 计算投影矩阵
    QMatrix4x4 projection;
    projection.perspective(fov, aspect, zNear, zFar);
    glLoadMatrixf(projection.constData());
    
    // 设置模型视图矩阵
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    
    // 优化相机位置
    QVector3D eye(0, 0, 20);
    QVector3D center(0, 0, 0);
    QVector3D up(0, 1, 0);
    
    QMatrix4x4 view;
    view.lookAt(eye, center, up);
    glMultMatrixf(view.constData());
}



void GLWidget::paintGL() {
    // 清除缓冲区
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    // 设置投影矩阵
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0f, width() / (float)height(), 0.1f, 500.0f);
    
    // 设置模型视图矩阵
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    
    // 相机变换
    glTranslatef(0, 0, -cameraDistance);
    glRotatef(rotationX, 1, 0, 0);
    glRotatef(rotationY, 0, 1, 0);
    glTranslatef(m_translation.x(), m_translation.y(), m_translation.z());

    // 绘制平面长方体
    for (const Plane &plane : planes)
    {
        glPushMatrix();
        glTranslatef(0.0f, 0.0f, plane.zLevel);

        // 设置平面颜色
        glColor4f(plane.gridColor.redF(), plane.gridColor.greenF(), plane.gridColor.blueF(), plane.gridColor.alphaF());

        float size = plane.size; // 长方体的尺寸
        float thickness = 0.6f; // 长方体的厚度
        glBegin(GL_QUADS);
        // 前表面
        glNormal3f(0, 0, 1);
        glVertex3f(-size, -size, thickness);
        glVertex3f(size, -size, thickness);
        glVertex3f(size, size, thickness);
        glVertex3f(-size, size, thickness);

        // 后表面
        glNormal3f(0, 0, -1);
        glVertex3f(-size, -size, -thickness);
        glVertex3f(-size, size, -thickness);
        glVertex3f(size, size, -thickness);
        glVertex3f(size, -size, -thickness);

        // 左表面
        glNormal3f(-1, 0, 0);
        glVertex3f(-size, -size, -thickness);
        glVertex3f(-size, -size, thickness);
        glVertex3f(-size, size, thickness);
        glVertex3f(-size, size, -thickness);

        // 右表面
        glNormal3f(1, 0, 0);
        glVertex3f(size, -size, -thickness);
        glVertex3f(size, size, -thickness);
        glVertex3f(size, size, thickness);
        glVertex3f(size, -size, thickness);

        // 顶表面
        glNormal3f(0, 1, 0);
        glVertex3f(-size, size, thickness);
        glVertex3f(size, size, thickness);
        glVertex3f(size, size, -thickness);
        glVertex3f(-size, size, -thickness);

        // 底表面
        glNormal3f(0, -1, 0);
        glVertex3f(-size, -size, thickness);
        glVertex3f(-size, -size, -thickness);
        glVertex3f(size, -size, -thickness);
        glVertex3f(size, -size, thickness);
        glEnd();
        glPopMatrix();

        // 绘制增强的3D节点
        for (int nodeIdx : plane.nodeIndices) {
            const Node& node = g_nodes[nodeIdx];
            drawEnhancedNode(node, plane.zLevel);
        }
    }
    
    // 绘制所有连接线
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_LINE_SMOOTH);
    glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
    
    for (const auto& connection : connections) {
        if (connection.node1 < g_nodes.size() && connection.node2 < g_nodes.size()) {
            const Node& node1 = g_nodes[connection.node1];
            const Node& node2 = g_nodes[connection.node2];
            drawConnection(node1, node2, connection.plane1, connection.plane2);
        }
    }
    
    glDisable(GL_LINE_SMOOTH);
    glDisable(GL_BLEND);
    glLineWidth(1.0f); // 重置线宽
}
// 修改鼠标事件处理函数
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (!isDragging) return;
    
    QPoint delta = event->pos() - lastMousePosition;
    
    // 右键或左键旋转 (改进用户体验)
    if (event->buttons() & (Qt::RightButton | Qt::LeftButton)) {
        float rotationSpeed = 0.3f;
        targetRotationX += delta.y() * rotationSpeed;
        targetRotationY += delta.x() * rotationSpeed;
        
        // 移除垂直旋转角度限制，允许360度旋转
        // targetRotationX = qBound(-89.0f, targetRotationX, 89.0f);
    }
    // 中键平移
    else if (event->buttons() & Qt::MiddleButton) {
        float panSpeed = 0.02f * (cameraDistance / 50.0f); // 根据距离调整平移速度
        m_translation += QVector3D(delta.x() * panSpeed, -delta.y() * panSpeed, 0);
    }

    lastMousePosition = event->pos();
}

void GLWidget::mousePressEvent(QMouseEvent *event) {
    lastMousePosition = event->pos();
    
    if (event->button() == Qt::LeftButton) {
        // 检查是否点击了节点
        int nodeIndex = getNodeAtPosition(event->x(), event->y());
        if (nodeIndex >= 0) {
            selectNode(nodeIndex);
        } else {
            clearSelection();
            update();
        }
    }
    
    isDragging = true;
    setCursor(Qt::ClosedHandCursor);
}

void GLWidget::mouseReleaseEvent(QMouseEvent *event) {
    Q_UNUSED(event)
    isDragging = false;
    setCursor(Qt::ArrowCursor);
}

void GLWidget::wheelEvent(QWheelEvent *event) {
    // 平滑缩放
    float zoomFactor = 1.0f + (event->angleDelta().y() / 1200.0f);
    targetCameraDistance /= zoomFactor;
    targetCameraDistance = qBound(minCameraDistance, targetCameraDistance, maxCameraDistance);
}

void GLWidget::updateCameraSmooth() {
    // 平滑插值
    float smoothFactor = 0.15f;
    
    rotationX += (targetRotationX - rotationX) * smoothFactor;
    rotationY += (targetRotationY - rotationY) * smoothFactor;
    cameraDistance += (targetCameraDistance - cameraDistance) * smoothFactor;
}



void drawSphere(float x, float y, float z, float radius) {
    int lats = 10;
    int longs = 10;
    for (int i = 0; i <= lats; i++) {
        float lat0 = M_PI * (-0.5 + (float)(i - 1) / lats);
        float z0 = sin(lat0);
        float zr0 = cos(lat0);

        float lat1 = M_PI * (-0.5 + (float)i / lats);
        float z1 = sin(lat1);
        float zr1 = cos(lat1);

        glBegin(GL_QUAD_STRIP);
        for (int j = 0; j <= longs; j++) {
            float lng = 2 * M_PI * (float)(j - 1) / longs;
            float x1 = cos(lng);
            float y1 = sin(lng);

            glNormal3f(x1 * zr0, y1 * zr0, z0);
            glVertex3f(x + radius * x1 * zr0, y + radius * y1 * zr0, z + radius * z0);
            glNormal3f(x1 * zr1, y1 * zr1, z1);
            glVertex3f(x + radius * x1 * zr1, y + radius * y1 * zr1, z + radius * z1);
        }
        glEnd();
    }
}

void GLWidget::drawConnection(const Node& node1, const Node& node2, int plane1Idx, int plane2Idx) {
    // 计算节点球心的绝对位置
    float plane1Height = (plane1Idx < planes.size()) ? planes[plane1Idx].zLevel : 0.0f;
    float plane2Height = (plane2Idx < planes.size()) ? planes[plane2Idx].zLevel : 0.0f;
    
    // 球心高度，与drawEnhancedNode中的nodeHeight一致
    const float nodeHeight = 2.0f;
    
    // 连线连接到球心位置
    float x1 = node1.relativeX;
    float y1 = node1.relativeY;
    float z1 = plane1Height + nodeHeight;  // 球心的Z坐标
    
    float x2 = node2.relativeX;
    float y2 = node2.relativeY;
    float z2 = plane2Height + nodeHeight;  // 球心的Z坐标
    
    // 如果是跨平面连接，使用不同的颜色和样式
    if (plane1Idx != plane2Idx) {
        glColor4f(1.0f, 0.5f, 0.0f, 0.8f); // 橙色，半透明
        glLineWidth(2.0f);
    } else {
        glColor4f(0.0f, 1.0f, 1.0f, 0.6f); // 青色，半透明
        glLineWidth(1.5f);
    }
    
    // 绘制连接线
    glBegin(GL_LINES);
    glVertex3f(x1, y1, z1);
    glVertex3f(x2, y2, z2);
    glEnd();
    
    // 如果是跨平面连接，添加一些装饰效果
    if (plane1Idx != plane2Idx) {
        // 在连线中点绘制一个小球体表示连接点
        float midX = (x1 + x2) / 2.0f;
        float midY = (y1 + y2) / 2.0f;
        float midZ = (z1 + z2) / 2.0f;
        
        glPushMatrix();
        glTranslatef(midX, midY, midZ);
        glColor4f(1.0f, 0.8f, 0.0f, 0.9f); // 金色
        drawSphere(0, 0, 0, 0.2f);
        glPopMatrix();
    }
}
